package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

var origins = []string{
	"http://localhost:5173",
	"http://localhost:3000",
	"http://localhost:11434",
}

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		//获取请求的的header的origin信息
		header := c.GetHeader("Origin")
		for _, origin := range origins {
			if origin == header {
				c.Header("Access-Control-Allow-Origin", origin)
				c.Header("Access-Control-Allow-Methods", "POST,PUT,DELETE, GET, OPTIONS")
				c.Header("Access-Control-Allow-Headers", "Content-Type")
			}

			if c.Request.Method == "OPTIONS" {
				c.JSON(http.StatusOK, "")
				c.Abort()
				return
			}
			c.Next()
		}

	}
}
